package com.fantsey.test.shortUrl.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fantsey.test.shortUrl.core.ShortUrlGenerator;
import com.fantsey.test.shortUrl.entity.ShortUrlEntity;
import com.fantsey.test.shortUrl.mapper.ShortUrlMapper;
import com.fantsey.test.shortUrl.service.IShortUrlService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fx
 * @since 2024-12-17
 */
@Service
public class ShortUrlServiceImpl extends ServiceImpl<ShortUrlMapper, ShortUrlEntity> implements IShortUrlService {

    @Override
    public ShortUrlEntity getFullUrlByShortCode(String shortCode) {
        LambdaQueryWrapper<ShortUrlEntity> shortUrlEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shortUrlEntityLambdaQueryWrapper.eq(ShortUrlEntity::getShortCode, shortCode);
        return this.getBaseMapper().selectOne(shortUrlEntityLambdaQueryWrapper);
    }

    @Override
    public Boolean addShortUrl(String fullUrl) {
        String shortUrlCode = ShortUrlGenerator.shortUrlCode(fullUrl)[0];
        ShortUrlEntity shortUrlEntity =  ShortUrlEntity.builder()
                .baseUrl(fullUrl.split("/")[2])
                .urlSuffix(fullUrl.split("/")[3])
                .fullUrl(fullUrl)
                .shortCode(shortUrlCode)
                .createTime(LocalDateTime.now())
                .createBy(1L)
                .expireTime(DateUtil.nextMonth().toLocalDateTime())
                .build();
       return getBaseMapper().insert(shortUrlEntity) > 0;
    }
}
